package Memmory;

import mainPackage.RealMachine;

public class VirtualMemmory {
        
    private int dataSegSize;
    private int codeSegSize;
    private Memmory realMemmory;
    private Word PTR;
    private RealMachine RM;
    
    public VirtualMemmory(RealMachine RM, int dataSegSize, int codeSegSize) {
        this.realMemmory = RM.MEMMORY;
        this.dataSegSize = dataSegSize;
        this.codeSegSize = codeSegSize;
        this.PTR = RM.PTR;
        this.RM = RM;
    }
    
    public int getDataSegSize() {
        return dataSegSize;
    }
    
    public int getCodeSegSize() {
        return codeSegSize;
    }
    
    public void putWord(Word word, int address) {
        realMemmory.putWord(word, this.translateToRealAddress(address));
    }
    
    public void putWord(Word word, int x, int y) {
        realMemmory.putWord(word, this.translateToRealAddress(x * RealMachine.BLOCK_SIZE + y));
    }
    
    public Word getWord(int x, int y) {
        return realMemmory.getWord(this.translateToRealAddress(x * RealMachine.BLOCK_SIZE + y));
    }
    
    public Word getWord(int address) {
        return realMemmory.getWord(this.translateToRealAddress(address));
    }
    
    public int translateToRealAddress(int virtualAddress) {
        int virtualMemX = virtualAddress / 16;
        int virtualMemY = virtualAddress % 16;
        
        int realMemX = realMemmory.getWord(PTR.getNumber(), virtualMemX).getNumber();
        int realMemY = virtualMemY;
        
        int realAddr = realMemX * RealMachine.BLOCK_SIZE + realMemY;
        
        if (virtualMemX < 0 || virtualMemX > RealMachine.VM_BLOCK_COUNT || virtualMemY < 0 || virtualMemY > RealMachine.BLOCK_SIZE) {
            RM.PI = 1;
        }
        
        return realAddr;
    }
    
}
